import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { NavBar } from 'antd-mobile';
import { QRCodeCanvas } from 'qrcode.react';
import './Com/Code.css';

// 格式化时间为北京时间
const formatBeijingTime = (): string => {
  const date = new Date();
  
  // 确保使用北京时间（UTC+8）
  const beijingTime = new Date(date.getTime() + (8 * 60 * 60 * 1000));
  
  const year = beijingTime.getUTCFullYear();
  const month = String(beijingTime.getUTCMonth() + 1).padStart(2, '0');
  const day = String(beijingTime.getUTCDate()).padStart(2, '0');
  const hours = String(beijingTime.getUTCHours()).padStart(2, '0');
  const minutes = String(beijingTime.getUTCMinutes()).padStart(2, '0');
  const seconds = String(beijingTime.getUTCSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

interface UserInfo {
  userId: string;
  nickname: string;
  avatar: string;
  phone: string;
  email: string;
  vipLevel?: number;
  points?: number;
}

interface PickupCode {
  orderId: string;
  productName: string;
  pickupCode: string;
  orderTime: string;
  deliveryAddress: string;
}

const Code: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [qrData, setQrData] = useState('');

  const handleBack = () => {
    navigate('/app/my');
  };

  useEffect(() => {
    // 从My.tsx传递的参数获取用户信息和提货码
    const passedUserInfo = location.state?.userInfo;
    const passedPickupCodes = location.state?.pickupCodes;
    
    // 确保pickupCodes是一个数组
    const pickupCodes: PickupCode[] = Array.isArray(passedPickupCodes) ? passedPickupCodes : [];
    
    let userInfo: UserInfo;
    
    if (passedUserInfo) {
      userInfo = {
        userId: passedUserInfo.userId || 'USR' + Date.now().toString().slice(-6),
        nickname: passedUserInfo.nickname || '社区用户',
        avatar: passedUserInfo.avatar || '',
        phone: passedUserInfo.phone || '138****8888',
        email: passedUserInfo.email || 'user@community.com',
        vipLevel: passedUserInfo.vipLevel || 1,
        points: passedUserInfo.points || 0
      };
    } else {
      userInfo = {
        userId: 'USR' + Date.now().toString().slice(-6),
        nickname: '社区用户',
        avatar: '',
        phone: '138****8888',
        email: 'user@community.com'
      };
    }
    
    // 构建提货码信息
    const pickupInfo = pickupCodes.map(pickup => 
      `订单: ${pickup.orderId}\n商品: ${pickup.productName}\n提货码: ${pickup.pickupCode}\n地址: ${pickup.deliveryAddress}`
    ).join('\n---\n');
    
         // 创建vCard格式的二维码数据，微信扫码后可以直接展示联系人信息和提货码
     const vCardData = `BEGIN:VCARD
VERSION:3.0
FN:${userInfo.nickname}
N:${userInfo.nickname};;;;
ORG:社区团购平台
TITLE:${userInfo.vipLevel ? `VIP${userInfo.vipLevel}会员` : '普通会员'}
TEL;TYPE=CELL:${userInfo.phone}
EMAIL:${userInfo.email}
NOTE:用户ID: ${userInfo.userId}${userInfo.points ? `\n积分: ${userInfo.points}` : ''}\n平台: 社区团购\n生成时间: ${formatBeijingTime()}${pickupInfo ? `\n\n=== 待提货信息 ===\n${pickupInfo}` : '\n暂无待提货订单'}
END:VCARD`;
    
    setQrData(vCardData);
  }, [location]);

  return (
    <div className="code-container">
      <NavBar onBack={handleBack} back="返回">
        提货码二维码
      </NavBar>
      <div className="code-content">
        <div className="qr-code-container">
          <div className="qr-code-wrapper">
            <QRCodeCanvas
              value={qrData}
              size={280}
              level="H"
              includeMargin={true}
              bgColor="#ffffff"
              fgColor="#000000"
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Code;